<template>
  <el-button type="success" @click="dialogTableVisible = true">
    新增角色
  </el-button>

  <el-table :data="tableData" border style="width: 100%">
    <el-table-column fixed type="index" label="编号" />
    <el-table-column prop="roleName" label="角色名">
      <template v-slot="a">
        <el-button link @click="getroleuser(a.row.id, a.row.roleName)"
          ><u>{{ a.row.roleName }}</u></el-button
        >
      </template>
    </el-table-column>
    <el-table-column prop="createName" label="创建人" />
    <el-table-column prop="createDate" label="创建日期" width="180px">
      <template v-slot="a">
        <span>{{
          a.row.createDate == null
            ? ""
            : moment(a.row.createDate).format("YYYY-MM-DD  HH:mm:ss")
        }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="updateName" label="修改人" />
    <el-table-column prop="updateDate" label="修改日期" width="180px">
      <template v-slot="a">
        <span>{{
          a.row.updateDate == null
            ? ""
            : moment(a.row.updateDate).format("YYYY-MM-DD  HH:mm:ss")
        }}</span>
      </template>
    </el-table-column>
    <el-table-column prop=" " label="操作" width="260px">
      <template v-slot="a">
        <el-button type="primary" @click="edit(a.row)">修改</el-button>
        <el-button type="danger" @click="del(a.row.id, a.row.roleName)"
          >删除</el-button
        >
        <el-button type="warning" @click="fenpei(a.row.id, a.row.roleName)"
          >分配人员</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!-- 新增角色 -->
  <el-dialog v-model="dialogTableVisible" title="新增角色" width="800">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="ruleForm.roleName" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 修改角色 -->
  <el-dialog v-model="dialogTableVisibleUpdate" title="编辑角色" width="800">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="ruleForm.roleName" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">
          修改
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 分配角色 -->
  <el-dialog
    v-model="dialogTableVisibleFenPei"
    :title="`请设置【${query.rolename}】角色的员工`"
    width="600"
  >
    <el-row :gutter="20">
      <el-col :span="10" style="margin-left: 40px">
        <el-tree
          ref="treeRef"
          style="max-width: 600px"
          class="filter-tree"
          :data="datadepartment"
          :props="defaultProps"
          default-expand-all
          v-model="query.departmentid"
          :filter-node-method="filterNode"
          @node-Click="nodeClick"
        />
      </el-col>
      <el-col :span="10">


        请选择员工
        <el-checkbox-group v-model="query.userId">
          <el-checkbox v-for="item in datauser"  :value="item.id" name="type">
            {{ item.userName }}
          </el-checkbox>
        </el-checkbox-group>

        <!-- <el-tree
        ref="userTreeRef"
        style="max-width: 600px"
        :data="datauser"
        show-checkbox
        node-key="id"
        :props="defaultProp"
        :default-expand-all="true"
      /> -->
      </el-col>
      <el-col :span="20">
        <el-button
          style="float: right; margin-top: 20px"
          type="primary"
          @click="createuserrole"
          >确定保存</el-button
        >
      </el-col>
    </el-row>
  </el-dialog>

  <!-- 角色中员工 -->
  <el-dialog
    v-model="dialogTableVisibleyuangong"
    width="600"
    style="height: 300px"
    :show-close="false"
  >
    <el-row class="role-dialog-container">
      <el-col :span="24" style="margin-left: 500px">
        <el-button link @click="dialogTableVisibleyuangong = false"
          ><b>"关闭"</b></el-button
        >
      </el-col>
      <el-col :span="24" style="margin-top: 50px; margin-left: 150px">
        <span style="margin: auto">{{
          `属于角色【${query.rolename}】的员工如下:`
        }}</span>
      </el-col>
      <el-col :span="22" class="user-list-container">
        <div class="user-item" v-for="item in tags" :key="item.userId">
          <span class="user-name">{{ item.userName }}</span>
          <el-button
            type="danger"
            link
            @click="delnewuser(item.userId, item.userName)"
            >×</el-button
          >
        </div>
      </el-col>
      <el-col :span="2" class="add-user-container">
        <el-button
          class="add-user-btn"
          type="success"
          link
          @click="addnewuser()"
          ><b>＋</b></el-button
        >
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from "vue";
import axios from "axios";
import moment from "moment";
import httpr from '@/axioslan/axioshttp'
import httpw from '@/axioslan/axioshttps'
onMounted(() => {
  search();
});
//显示角色信息
const tableData = ref([]);
const search = () => {
  httpr({
    url: "/api/Role/GetRole",
    method: "get",
  }).then((res) => {
    tableData.value = res.data.data;
  });
};

//新增角色
const dialogTableVisible = ref(false);
import {
  ElMessage,
  ElMessageBox,
  ElTree,
  type FormInstance,
  type FormRules,
} from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  id: "",
  roleName: "",
});

const rules = reactive<FormRules>({
  roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      httpw({
        url: "/api/Role/CreateRole",
        method: "post",
        data: ruleForm,
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          search();
          dialogTableVisible.value = false;
          ruleForm.roleName = "";
          return;
        } else {
          ElMessage.error(res.data.msg);
          search();
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
//编辑角色
const dialogTableVisibleUpdate = ref(false);
const edit = async (row: any) => {
  console.log(row);
  Object.assign(ruleForm, row);

  dialogTableVisibleUpdate.value = true;
};

const submitFormUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      httpw({
        url: "/api/Role/UpdateRole",
        method: "put",
        data: ruleForm,
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          search();
          dialogTableVisibleUpdate.value = false;
          ruleForm.roleName = "";
          return;
        } else {
          ElMessage.error(res.data.msg);
          search();
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//删除角色
const del = (id: any, name: any) => {
  ElMessageBox.confirm("您确认要删除角色[" + name + "]的信息吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      httpw({
        url: "/api/Role/DelRole",
        method: "delete",
        params: {
          id: id,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          search();
          return;
        } else {
          ElMessage.error(res.data.msg);
          search();
          return;
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

//分配
const dialogTableVisibleFenPei = ref(false);
const fenpei = (id: any, name: any) => {
  newroleid = id;
  newrolename = name;
  query.rolename=name;
  fantianuseris(id);
  dialogTableVisibleFenPei.value = true;
};

//树型部门
import type { FilterNodeMethodFunction, TreeInstance } from "element-plus";

interface Tree {
  [key: string]: any;
}

const filterText = ref("");
const treeRef = ref<TreeInstance>();

const defaultProps = {
  children: "children",
  label: "label",
};

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});

const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};

//树形控件节点点击事件
const nodeClick = (x: any) => {
  console.log(x);
  getuser(x.id);
};

const datadepartment: Tree[] = [
  {
    id: 0,
    label: "请选择部门",
    children: [
      {
        id: 1,
        label: "IT信息部",
      },
      {
        id: 2,
        label: "人力资源部",
      },
      {
        id: 3,
        label: "财务部",
      },
      {
        id: 4,
        label: "销售部",
      },
      {
        id: 5,
        label: "行政部",
      },
    ],
  },
];



const userTreeRef=ref<InstanceType<typeof ElTree>>();
const datauser: any = ref([]);

//显示部门下员工的树形
const defaultProp:any = {

  id: 'id',
  label: 'userName',
  children: [{label:"请选择用户"}],
}

const getuser = (id: any) => {
  httpr({
    url: "/api/User/GetUserByDepartmentId",
    method: "get",
    params: {
      departmentId: id,
    },
  }).then((res) => {
    datauser.value = res.data.data;
  });
};

const query: any = reactive({
  roleId: "",
  rolename: "",
  userId:[],
  departmentId: "",
});

const usernamelist = ref([]);

//根据角色反填用户
const fantianuseris = (id: any) => {
  httpr({
    url: "/api/Role/FanTianUserIdByRoleId",
    method: "get",
    params: {
      roleid: id,
    },
  }).then((res) => {
    if (
      !res.data.data ||
      !Array.isArray(res.data.data) ||
      res.data.data.length === 0
    ) {
      query.roleId = "";
      query.userId = [];
      usernamelist.value = [];
      datauser.value = [];
      return;
    }

    const data = res.data.data;

    getuser(data[0].departmentId);
    {
      query.departmentId = data.map((item: any) => item.departmentId);
    }

    query.userId = data.map((item: any) => item.userId);

    usernamelist.value = data.map((item: any) => item.userName);
    //  userTreeRef.value?.setCheckedKeys(query.userId,true)
  });
};

//为用户分配角色
const createuserrole = () => {

  query.roleId = newroleid;

  // query.userId = userTreeRef.value!.getCheckedKeys(false)

  httpw({
    url: "/api/Role/CreateUserRole",
    method: "post",
    data: query,
  }).then((res) => {
    console.log(res);

    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      search();
      dialogTableVisibleFenPei.value = false;
      getroleuser(newroleid, newrolename);

      query.roleId = "";
      query.userId = [];
      datauser.value = [];
      return;
    } else {
      ElMessage.error(res.data.msg);
      search();
    }
  });
};

//当前角色所有的员工
let newroleid = 0;
let newrolename = "";
const dialogTableVisibleyuangong = ref(false);
const getroleuser = (id: any, name: any) => {
  query.roleId = id;
  query.rolename = name;
  fantianuseris(id);
  getnewroleuser(id);
  newroleid = id;
  newrolename = name;
  dialogTableVisibleyuangong.value = true;
};

//按＋号为角色增加用户
const addnewuser = () => {
  fenpei(newroleid, newrolename);
};

const tags: any = ref([
  {
    userId: 0,
    roleId: 0,
    userName: "",
    departmentId: 0,
  },
]);

const getnewroleuser = (id: any) => {
  httpr({
    url: "/api/Role/FanTianUserIdByRoleId",
    method: "get",
    params: {
      roleid: id,
    },
  }).then((res) => {
    tags.value = res.data.data;
  });
};

//按×为角色删除用户
const delnewuser = (id: any, name: any) => {
  ElMessageBox.confirm(
    "确认要删除角色" + newrolename + "里的用户" + name + "吗?",
    "警告",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      httpw({
        url: "/api/Role/DeleteUserRoleByUserId",
        method: "delete",
        params: {
          roleid: newroleid,
          userId: id,
        },
      }).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          getroleuser(newroleid, newrolename);
          return;
        } else {
          {
            ElMessage.error(res.data.msg);
            fantianuseris(newroleid);
            return;
          }
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
</script>

<style>
.tooltip-base-box {
  width: 600px;
}
.tooltip-base-box .row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tooltip-base-box .center {
  justify-content: center;
}
.tooltip-base-box .box-item {
  width: 110px;
  margin-top: 10px;
}

/* 新增用户列表样式 */
.role-dialog-container {
  position: relative;
  min-height: 200px;
}

.user-list-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 20px;
  margin-top: 20px;
  border-right: 1px solid #ebeef5;
}

.add-user-container {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 100%;
  padding-top: 90px;
}

.add-user-btn {
  font-size: 20px;
  height: 40px;
  width: 40px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.user-item {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 5px 10px;
  border-radius: 4px;
  max-width: calc(100% - 20px);
  word-break: break-all;
}

.user-name {
  margin-right: 5px;
  flex: 1;
  overflow-wrap: break-word;
  word-wrap: break-word;
}
</style>
